package com.kunyi.web.im.websocket.config;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Properties;

/**
 * @ClassName NacosClientRegister
 * @Description nacos客户端注册到nacos上面，因为本服务不以http内部容器启动不会自动注册
 * @Author huangxiaoqin
 * @Date 2024/4/10 16:13
 * @Version 1.0
 */
@Component
@Slf4j
public class NacosClientRegister {

    @Value("${transport.websocket.bind_port}")
    private Integer port;
    /***
     * @author: huangxiaoqin
     * @Description 注册当前服务
     * @Date 16:14 2024/4/10
     * @Param :
     * @return void
     **/
    public void registerService() throws Exception{
        try {
            Properties props = System.getProperties();
            String serverAddr = props.getProperty("kunyi.nacos.addr");
            String namespace = props.getProperty("kunyi.nacos.namespace");
            String username = props.containsKey("kunyi.nacos.username")?props.getProperty("kunyi.nacos.username"):"";
            String password = props.containsKey("kunyi.nacos.password")?props.getProperty("kunyi.nacos.password"):"";
            //构建核心参数
            Properties properties = new Properties();
            properties.setProperty("serverAddr", serverAddr);
            properties.setProperty("namespace", namespace);
            properties.setProperty("username",username);
            properties.setProperty("password",password);

            //获取nacos的服务管理对象
            NamingService namingService = NamingFactory.createNamingService(properties);
            //将服务注册到注册中心
            InetAddress addr = InetAddress.getLocalHost();
            namingService.registerInstance("kunyi-im-WebSocket", addr.getHostAddress(), port);
            log.info("服务注册成功");
        } catch (NacosException e) {
            log.error("服务注册失败", e);
        }
    }
}
